<template>
	<view class="count_box">
		<canvas class="count_box_bg" style="width: 300px; height: 300px;position: absolute;top: 0;left: 0;z-index: 0;" id="countbg" canvas-id="countbg"></canvas>
		<canvas style="width: 300px; height: 300px;position: relative;" id="countdowncvs" canvas-id="countdowncvs"></canvas>
	</view>
</template>

<script>
	/**
	 * Badge 数字角标
	 * @description 数字角标一般和其它控件（列表、9宫格等）配合使用，用于进行数量提示，默认为实心灰色背景
	 * @tutorial https://ext.dcloud.net.cn/plugin?id=21
	 * @property {String} text 角标内容
	 * @property {String} type = [default|primary|success|warning|error] 颜色类型
	 * 	@value default 灰色
	 * 	@value primary 蓝色
	 * 	@value success 绿色
	 * 	@value warning 黄色
	 * 	@value error 红色
	 * @property {String} size = [normal|small] Badge 大小
	 * 	@value normal 一般尺寸
	 * 	@value small 小尺寸
	 * @property {String} inverted = [true|false] 是否无需背景颜色
	 * @event {Function} click 点击 Badge 触发事件
	 * @example <uni-badge text="1"></uni-badge>
	 */
	let _this;
	export default {
		name: 'Countdown',
		props: {
			type: {
				type: String,
				default: 'default'
			},
			time: {
				type: [String, Number],
				default: 1
			},
			fillTime: {
				type: [String, Number],
				default: 1
			},
			color: {
				type: String,
				default: '#007AFF'
			},
			stop:{
				type: Boolean,
				default: false
			},
			size: {
				type: String,
				default: 'normal'
			}
		},
		data() {
			return {
				badgeStyle: '',
				timer: null,
				// countdownStop: this.stop
			};
		},
		mounted() {
			_this = this
			if(this.time>0) {this.createCountdown()}else{
				console.log('初始化失败',this.time)
			};
		},
		watch: {
			text() {
				this.setStyle()
			},
			time(){
				if(this.time>0) {this.createCountdown()}else{
				};
			},
			stop(val,oldVal){
				if(val){
					clearTimeout(_this.timer)
					this.$emit("stoped", val);
				}
			}
		},
		beforeDestroy() {
			clearTimeout(this.timer)
		},
		methods: {
			onClick() {
				this.$emit('click');
			},
			createCountdown() {
				_this = this
				clearTimeout(this.timer)
				let ctx = uni.createCanvasContext('countdowncvs', this)
				let ctxBg = uni.createCanvasContext('countbg',this)
				let lineWidth = 20;
				let r = 300 / 2; //中间位置
				let cR = r - 2 * lineWidth; //圆半径
				let startAngle = -(1 / 2 * Math.PI); //开始角度
				let endAngle = startAngle - 2 * Math.PI; //结束角度
				let xAngle = 1 * (Math.PI / (600 * this.fillTime / 60)); //偏移角度量
				let fontSize = 35; //字号大小
				let tmpAngle = startAngle - (this.fillTime - this.time) * 20 * xAngle; //临时角度变量
				let remainingTime = this.time * 1000
				
				ctxBg.setLineWidth(lineWidth)
				ctxBg.setStrokeStyle("#EEE")
				ctxBg.arc(r, r, cR, 0, 2 * Math.PI, true)
				ctxBg.stroke()
				ctxBg.draw()

				//渲染函数
				let rander = function() {
					if ((tmpAngle <= endAngle || _this.stop) && _this.time > 0) {
						// _this.countdown(-1)
						clearTimeout(_this.timer)
						return;
					} else if (tmpAngle - xAngle < endAngle) {
						tmpAngle = endAngle;
					} else {
						tmpAngle -= xAngle;
					}
					ctx.clearRect(0, 0, 300, 300);
					//画圈
					ctx.beginPath();
					ctx.setLineWidth(lineWidth);
					ctx.setLineCap('round')
					var g = ctx.createLinearGradient(0,0,180,180);  //创建渐变对象  渐变开始点和渐变结束点
					g.addColorStop(0, '#abe9ff'); //添加颜色点
					g.addColorStop(1, '#007AFF'); //添加颜色点
					// g.addColorStop(0.667, '#A9D25B'); //添加颜色点
					// g.addColorStop(1, '#FA5A2D'); //添加颜色点
					ctx.setStrokeStyle(g);
					ctx.arc(r, r, cR, startAngle, tmpAngle);
					ctx.stroke();
					ctx.closePath();
					//写字
					ctx.setFillStyle('#007AFF');
					ctx.font = fontSize + 'px Microsoft Yahei';
					ctx.setTextAlign('center');
					ctx.fillText(_this.countdown((remainingTime -= 50)/1000), r, r + fontSize / 2);
					ctx.draw()
					_this.timer = setTimeout(() => {
						rander()
					}, 50);
					
				};
				rander();
			},
			// 消费倒计时
			countdown(time) {
				if (time > 0) {
					let H = (time / 3600).toString().substring(0, 1)
					let m = (time / 60 % 60).toString().substring(0, 2).replace('.', '')
					let s = (time % 60).toFixed(0).toString()
					return `${H < 10 ? ('0' + H) : H}:${m < 10 ? ('0' + m) : m}:${s < 10 ? ('0' + s) : s}`
				} else {
					this.stop = true
					return '消费结束'
				}
			},
		}
	};
</script>

<style scoped lang="scss">
	.count_box {
		width: 300px;
		height: 300px;
		position: relative;
	}
</style>
